import React, { useState, useEffect } from 'react';
import s from './style.module.less';
import cn from 'classnames';
import i from '@/index.module.css';
import { filterNull } from '@/utils';
import { operateLogModule, operateLogList } from '~/API/index';
import moment from 'moment';
import { getErrorMessage } from '@/common/constant';
import {
  Select,
  Input,
  Pagination,
  Table,
  Message,
  Dialog,
  Datetime,
  Loading,
  Button
} from '@knownsec/react-component';

export default function ActionLog({topExport, updateFlag}) {
  const dateFormat = 'YYYY-MM-DD';
  const today = ['', ''];
  const [now, setNow] = useState(today);
  const [loading, setLoading] = useState(false);
  const [modules, setModule] = useState([]);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [count, setCount] = useState(0);
  const [detail, setDetail] = useState('');
  const [detailVisible, setDetailVisible] = useState(false);
  const [tableData, setTableData] = useState([]);
  const [subModule, setSubModule] = useState([]);
  const [moduleItem, setModuleItem] = useState('');
  const [valueDict, setValueDict] = useState({
    module: '',
    type: '',
    start_date: '',
    end_date: '',
    ip: '',
    operator: '',
  });
  
  
  const openDetail = (t) => {
    setDetail(t);
    setDetailVisible(true);
  };
  const columns = [
    { title: '操作人', key: 'operator',className: s.w_7, dataIndex: 'operator' },
    { title: '角色', key: 'group',className: s.w_7, dataIndex: 'group', render: (val) => val?.length?val.join('、'):'-'},
    { title: '登录IP', key: 'ip', dataIndex: 'ip' },
    { title: '操作时间', key: 'time', dataIndex: 'time',render: (val) => val?moment(val).format('YYYY-MM-DD HH:mm:ss'):'-' },
    { title: '模块', key: 'module', dataIndex: 'module' },
    { title: '子模块', key: 'type', dataIndex: 'type' },
    {
      title: '操作',
      key: 'desc',
      dataIndex: 'desc',
      render: (cur, item) => {
        return (
          <span className={cn(i.mainColor, i.cp)} onClick={() => openDetail(item.desc.detail)}>
            查看详情
          </span>
        );
      },
    },
  ];
  function getTableData(page, pageSize, data = {}) {
    data = filterNull(data)
    const sdata = Object.assign({page: page, pageSize: pageSize}, data)
    setLoading(true)
    operateLogList('GET', sdata).then((res) => {
      setLoading(false)
      setCount(res.data?.count);
      setTableData(res.data?.data);
    });
  }
  function changeQuery(val, type) {
    setPage(1);
    setPageSize(10);
    const d = Object.assign({},valueDict)
    if(type === 'module'){
      d.module = val.length?val[0].value:''
    }else{
      d.type = val.length?val[0].value:''
      getTableData(1,10,d)
    }
    setValueDict(d)
  }
  useEffect(() => {
    console.log(updateFlag, valueDict.module)
    operateLogModule('GET', valueDict.module)
      .then((res) => {
        const rd = res.data || {}
        const moduleArr = Object.entries(rd.module).map((item) => {
          return { label: item[0], value: item[1] };
        });
        const submoduleArr = Object.entries(rd.submodule).map((item) => {
          return { label: item[0], value: item[1] };
        });
        setModule(moduleArr);
        setSubModule(submoduleArr);
      })
      .catch((err) => Message.show({ type: 'error', message: getErrorMessage(err) }));
    // const p = 
    getTableData(page,pageSize,valueDict);
  }, [valueDict.module, updateFlag]);
  const disabledate = (current) => {
    return current > moment();
  };
  
  const onSearchChange = (key, obj) => {
    let d = {}
    if(key === 'time'){
      d = filterNull(obj)
    }else{
      d = filterNull(valueDict)
      if(key)
        d[key] = ''
    }
    setPage(1);
    setPageSize(10);
    getTableData(1,10,d);
  };
  return (
    <div className={cn(s.actionlog)}>
      <div className={s.searchBox}>
        {topExport()}
        <div className={cn(s.searchRight, s.mb10)}>
          <Input
            pro
            placeholder="操作人"
            value={valueDict.operator}
            autoComplete={'off'}
            className="searchName search-button"
            search
            onSearch={onSearchChange}
            clear
            onChange={({value}) => {
              let obj = Object.assign({}, valueDict);
              obj.operator = value;
              setValueDict(obj);
              if (!value) {
                onSearchChange('operator');
              }
            }}
          ></Input>
          <Input
            pro
            placeholder="登录IP"
            value={valueDict.ip}
            autoComplete={'off'}
            className="searchName search-button"
            search
            onSearch={onSearchChange}
            clear
            onChange={({value}) => {
              let obj = Object.assign({}, valueDict);
              obj.ip = value;
              setValueDict(obj);
              if (!value) {
                onSearchChange('ip');
              }
            }}
          ></Input>
          <Select
            option={modules}
            pro
            placeholder="请选择模块"
            className={s.selectItem}
            clearable
            searchable
            value={[valueDict.module]}
            onChange={({ selectedItem }) => changeQuery(selectedItem, 'module')}
          />
          <Select
            option={subModule}
            pro
            searchable
            placeholder="请选择子模块"
            className={s.selectItem}
            clearable
            value={[valueDict.type]}
            onChange={({ selectedItem }) => changeQuery(selectedItem, 'type')}
          />
          <Datetime
            disabledDate={disabledate}
            className={cn(s.radiu)}
            value={now}
            onChange={(val) => {
              val = val || ['', '']
              setNow(val);
              let obj = Object.assign({}, valueDict);
              obj.start_date = val[0]?moment(val[0]._d).toJSON():'';
              obj.end_date = val[1]?moment(val[1]._d).toJSON():'';
              setValueDict(obj);
              onSearchChange('time', obj)
            }}
          />
        </div>
      </div>
      <Table columns={columns} data={tableData} tableLoading={loading} loadingLabel="" />
      <div className={cn(i.pt20, i.df, i.aic, i.jcfe, i.pb20)}>
        {count> 10 && <Pagination
          total={count}
          showQuickJumper={{ goButton: true }}
          showTotal={(total) => `共${total}条`}
          showSizeChanger={true}
          pageSizeOptions={['10', '20', '50']}
          current={page}
          onChange={(page,size) => {
            setPage(page)
            setPageSize(size);
            getTableData(page,size,valueDict)
          }}
        />}
      </div>
      <Dialog
        title="日志详情"
        visible={detailVisible}
        cusCancel={<Button type="default" onClick={() => setDetailVisible(false)}>关闭</Button>}
        confirmText=""
        className={s.w500}
        onhide={() => setDetailVisible(false)}
      >
        <div className={cn(i.pt20, i.pl30, i.pr30, i.tac, s.mh200)}>{detail}</div>
      </Dialog>
    </div>
  );
}
